package com.lmf.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;


/**
 * 利用完全注解开发
 */
@Configuration      //作为配置类
@ComponentScan(basePackages = "com.lmf")    //开启注解扫描
@EnableTransactionManagement    //开启事务
@Service
public class TxConfig {
    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///user_db?characterEncoding=UTF-8");
        dataSource.setUsername("root");
        dataSource.setPassword("552200");
        return dataSource;
    }
    //创建JdbcTemplate模板对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate=new JdbcTemplate();
        //注入数据库
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
    //创建事务管理器对象
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager2=new DataSourceTransactionManager();
        //注入数据源,指定哪个数据库的事务管理
        transactionManager2.setDataSource(dataSource);
        return transactionManager2;
    }
}
